package com.fz.aop.log;

import com.fz.dto.merchant.merLogin.MerLoginDto;
import com.fz.dto.system.login.LoginSysDto;
import com.fz.entity.log.MerLoginLog;
import com.fz.mapper.log.MerLoginLogMapper;
import com.fz.utils.IpUtils;
import com.fz.utils.JacksonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 *  商户平台登录日志
 */
@Component
@Aspect
@SuppressWarnings("unchecked")
public class UserLoginLogAspect {


    @Resource
    private MerLoginLogMapper merLoginLogMapper;
   /**
    * @方法描述: 定义切点
    * @参数:
    * @返回值:
    * @创建人: I am God
    * @创建时间:: 2021/2/23
    */
    @Pointcut("execution(* com.fz.controller.merchant.MerLoginController.login*(..))")
    public void pointCutLogin() {}

    /**
     * 环绕通知获取请求与返回
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @AfterReturning(value = "pointCutLogin()", returning="returnValue")
    public void afterReturnLogin(JoinPoint joinPoint,Object returnValue) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        MerLoginDto merLoginDto = null;
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                if("merLoginDto".equals(argNames[i])){
                    merLoginDto = (MerLoginDto)argValues[i];
                }
            }
        }
        MerLoginLog loginLog = new MerLoginLog();
        loginLog.setLoginId(merLoginDto.getLoginid());
        loginLog.setIp(IpUtils.getIpAddr(request));
        loginLog.setResponse(JacksonUtils.obj2String(returnValue));
        merLoginLogMapper.insert(loginLog);
    }
}
